101.変数ベースの単一キャラ

変数ベースの単一キャラの例です。ここから理解をスタートしましょう。

p5.js oop
Learning OOP Object Oriented Programming

まずは1つのキャラを動かすために座標、スピードなどを変数宣言します。
丸を1つ動かすプログラムは作ったことはあると思います。
今回はマウスについていくのではなく、自動で動くプログラムになっています。

  • 変数宣言
  • 関数宣言
  • setup(), draw() で各関数を呼び出しています。

確認:変数・関数の理解はOK?

この時点で変数、関数が理解できない人は、まだオブジェクト指向プログラミングの学習に進むのは時期尚早です。 いますぐ引き返して基礎を学びましょう!

View Source Code

let W, H, PW, PH;
const PADDING_RATIO = 0.2;
const MAX_SPEED = 10;

let x, y, xSpeed, ySpeed, acceleration;

function prepare() {
  x = random(width);
  y = random(height);
  xSpeed = (Math.random() - 0.5) * MAX_SPEED;
  ySpeed = (Math.random() - 0.5) * MAX_SPEED;
  acceleration = 0.1;
}

function update() {
  x += xSpeed;
  y += ySpeed;

  if (x < 0 + PW) {
    xSpeed += acceleration;
  } else if (x > W - PW) {
    xSpeed -= acceleration;
  }

  if (y < 0 + PH) {
    ySpeed += acceleration;
  } else if (y > H - PH) {
    ySpeed -= acceleration;
  }
}

function display() {
  stroke(0);
  fill(0);
  ellipse(x, y, 10, 10);
  text(["1:", Math.floor(x), Math.floor(y)], x + 10, y + 10);
}

// main

function setup() {
  createCanvas((W = windowWidth), (H = windowHeight));
  PW = W * PADDING_RATIO;
  PH = H * PADDING_RATIO;

  prepare();
}

function draw() {
  background(255);

  update();
  display();
}